package softisoft.impcontacts;



import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.os.Handler;
import android.app.Dialog;
import android.os.Message;
import android.app.ProgressDialog;

public class ImportContactsActivity extends Activity {
    
	private static final int REQUEST_SAVE = 1;
	private static final int REQUEST_LOAD = 0;
    private String filePath = "No file path";
    private Spinner s;
    private EditText filePathEditText;

    
    ProgressThread progThread;
    ProgressDialog progDialog;
    Button button1, button2;
    int typeBar;                      // Milliseconds of delay in the update loop
    int loaded = 50;           // Maximum value of horizontal progress bar
    
    
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
        	 // fill the combo box 
            s = (Spinner) findViewById(R.id.spinner1);
                          
            @SuppressWarnings("rawtypes")
    		ArrayAdapter adapter = ArrayAdapter.createFromResource(
                    this, R.array.file_types, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s.setAdapter(adapter);
            
            
            Button browseButton = (Button) findViewById(R.id.browseButton);
            browseButton.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    				findFile();
    			}
            });
            
            Button loadButton = (Button) findViewById(R.id.loadButton);
            loadButton.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    				loadContacts();
    			}
            });
            
            Button importButton = (Button) findViewById(R.id.importButton);
            importButton.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    				typeBar = 1;
                    showDialog(typeBar);
    			}
            });
            
            filePathEditText = (EditText) findViewById(R.id.editText1);
            
		} catch (Exception e) {
			showAlert("Error", e.getMessage());
		}
       
        
    }
    
    public void findFile(){
    	try {
    		Intent intent = new Intent(this.getBaseContext(),FileDialog.class);
        	intent.putExtra(FileDialog.START_PATH, "/sdcard");
    		this.startActivityForResult(intent, REQUEST_SAVE);
    		
		} catch (Exception e) {
	    	showAlert("Erorr", e.getMessage());
		}
    }
    
    public void loadContacts(){
    	try {
    		CSVParser.filePath = filePath;
			if (CSVParser.openReader()) {
				loaded = CSVParser.read()-1;
			}
			else{
				showAlert("Erorr",CSVParser.erorr);
			}
			showAlert("Succes","Loaded: " +  loaded  + " contacts.");
		} catch (Exception e) {
			showAlert("Erorr",CSVParser.erorr);
		}   
		CSVParser.closeReader(); 	    	
    }
    
    public void insertContact(Contact  c){
    	try {
    		  		
    		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                    .build());
            // -------------------------- IME ---------------------------
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, c.getName())
                    .build());
          // -------------------------- BROJ ---------------------------
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, c.getPhone())
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE)
                    .build());
         // -------------------------- EMAIL ---------------------------
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA, c.getEmail())
                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE, Email.TYPE_HOME)
                    .build());
               getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);             
            } catch (Exception e) {
                showAlert("Erorr",e.getMessage());
            }
    }
    
    public synchronized void onActivityResult(final int requestCode,
            int resultCode, final Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                    if (requestCode == REQUEST_SAVE) {
                    	filePath = data.getStringExtra(FileDialog.RESULT_PATH);
                    	filePathEditText.setText(filePath);
                    } else if (requestCode == REQUEST_LOAD) {
                            System.out.println("Loading...");
                    }
            } else if (resultCode == Activity.RESULT_CANCELED) {
            	filePath = "Erorr";
            }

    }
    
    public void showAlert(String title,String message){
    	AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    	alertDialog.setTitle(title);
    	alertDialog.setMessage(message);
    	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    	   public void onClick(DialogInterface dialog, int which) {
    	      // here you can add functions
    	   }
    	});
    	alertDialog.setIcon(R.drawable.icon);
    	alertDialog.show();
    }
    
    
    // Method to create a progress bar dialog of either spinner or horizontal type
    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case 0:                      // Spinner
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progDialog.setMessage("Importing contacts...");
            progThread = new ProgressThread(handler);
            progThread.start();
            return progDialog;
        case 1:                      // Horizontal
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progDialog.setMax(loaded);
            progDialog.setMessage("Importing contacts...");
            progThread = new ProgressThread(handler);
            progThread.start();
            return progDialog;
        default:
            return null;
        }
    }
    
    // Handler on the main (UI) thread that will receive messages from the 
    // second thread and update the progress.
    
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // Get the current value of the variable total from the message data
            // and update the progress bar.
            int inserted = msg.getData().getInt("inserted");
            progDialog.setProgress(inserted);
            if (inserted == loaded){
                dismissDialog(typeBar);
                progThread.setState(ProgressThread.DONE);
            }
        }
    };

    
    private class ProgressThread extends Thread {	
        
        // Class constants defining state of the thread
        final static int DONE = 0;
        final static int RUNNING = 1;
        
        Handler mHandler;
        int mState;
        int inserted = 0;
    
        ProgressThread(Handler h) {
            mHandler = h;
        }        
        @Override
        public void run() {
            mState = RUNNING;   
            while (mState == RUNNING) {
                
                for (Contact  c: CSVParser.contacts) {
					Message msg = mHandler.obtainMessage();
					Bundle b = new Bundle();
                	insertContact(c);
                	inserted++;
					b.putInt("inserted", inserted);
					msg.setData(b);
					mHandler.sendMessage(msg);            		
				}
            }
        }
                
        public void setState(int state) {
            mState = state;
        }
    }
}